package rejjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import rejjie.dto.DishDto;
import rejjie.entity.Dish;
import rejjie.entity.DishFlavor;
import rejjie.mapper.DishFlavorMapper;
import rejjie.mapper.DishMapper;
import rejjie.service.DishFlavorService;
import rejjie.service.DishService;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 增加菜品  不光要增加 dish表 菜品的基本信息
     * 还要对 dishflavor 表 进行操作， 保存菜品的口味信息
     * 对于多次数据库操作的我们需要加事务注解
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        // 增加菜品
        this.save(dishDto);
        log.info("{}",dishDto);

        //获取增加菜品的id
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();

        // 使用遍历的形式 每一个口味爱好加到dishflavor表中
        flavors = flavors.stream().map((item) -> {
            // 放入菜品的id
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 通过id查询菜品信息 同时查询口味信息s
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        // 根绝id得到我们想要的菜品的信息
        Dish dish = this.getById(id);

        BeanUtils.copyProperties(dish,dishDto);

        //根据菜品id查询我们想要的口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishDtolist = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(dishDtolist);

        return dishDto;
    }


}
